<?php

namespace App\Models\Factory;

use App\Helpers\Generator\TokenGenerator;
use App\Helpers\Utils;
use App\Models\AbsModelFactory;
use App\Models\Orm\VipLog;
use App\Models\Orm\PaySetting;
use App\Models\Factory\UserFactory;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;

/**
 * 充值支付工厂
 * Class RechargeFactory
 * @package App\Models\Factory
 */
class RechargeFactory extends AbsModelFactory
{

  	/**
  	 * 共有的验证方法
  	 */
  	private static function checkout($money,$userinfo)
  	{
  		  if(empty($money)){
       		return 4000;
        }

        if(empty($userinfo)){
       		return 1003;
        }

        return 1;
  	}

    /**
     * 共有入订单表
     */
    private static function insertMoney($userinfo,$orderid,$money,$type)
    {
        $log['user_id']     = $userinfo->id;
        $log['order_id']    = $orderid;
        $log['amount']      = $money;
        $log['status']      = 1;
        $log['pay_method']  = $type;
        $log['created_at']  = date("Y-m-d H:i:s");
        $res = VipLog::insert($log);
        if(!$res){
          return 2000;
        }
        return 1;
    }


	/**
	 * 微信app支付
	 */
    public static function wxPayApp($request,$token)
    {
        $money   = (int)$request['money'] ? : 0;

        //获取用户信息
        $userinfo = UserFactory::getUserByToken($token);
        
        $code = self::checkout($money,$userinfo);

        if($code!=1){
        	return $code;
        }

        $money = $money/100;

        //money_log订单ID
        $orderid = TokenGenerator::generateToken();
        $insert = self::insertMoney($userinfo,$orderid,$money,1);
        if($insert!=1){
          return $insert;
        }

        //查询支付配置
        $pay = PaySetting::where("status",1)->where("type",1)->limit(1)->get()->toArray();

    		$order = [
    			'out_trade_no' => $orderid,
    			'total_fee'    => $money*100, // **单位：分**
    			'body'         => '幸运购'
        ];

        $config = [
    			'appid'      => $pay['0']['extend'], // APP APPID
    			'mch_id'     => $pay['0']['mid'],
    			'key'        => $pay['0']['key'],
    			'notify_url' => $_SERVER['HTTP_HOST'].'/v2/recharge/wxappnotify',
    		];

        $info = Pay::wechat($config)->app($order);
        $arr = (array)$info;

        foreach($arr as $key => $val){
          $result[]=json_decode($val,true);
        }
        return $result[0];
    }



    /**
     * 支付宝app支付
     *
     */
  	public static function aliPayApp($request,$token)
  	{
        $money   = (int)$request['money'] ? : 0;

        //获取用户信息
        $userinfo = UserFactory::getUserByToken($token);
        
        $code = self::checkout($money,$userinfo);

        if($code!=1){
        	return $code;
        }

        $money = $money/100;

        //money_log订单ID
        $orderid = TokenGenerator::generateToken();
        $insert = self::insertMoney($userinfo,$orderid,$money,2);
        if($insert!=1){
          return $insert;
        }

        //查询支付配置
        $pay = PaySetting::where("status",1)->where("type",2)->limit(1)->get()->toArray();

    		$config = [
    			'app_id'         => $pay['0']['mid'],
          'notify_url'     => $_SERVER['HTTP_HOST'].'/v2/recharge/alinotify',
          'ali_public_key' => $pay['0']['extend'],
          'private_key'    => $pay['0']['key'],
    		];

    		$order = [
            'out_trade_no' => $orderid,
            'total_amount' => $money,
            'subject'      => '幸运购',
    		];
    		$info = Pay::alipay($config)->app($order);
        unset($info->headers);

        $arr = (array)$info;

        foreach($arr as $key => $val){
          $data[] = $val;
        }
        $solve = explode('&', $data['0']);
        $result=array();
        foreach($solve as $key => $val){
          $transition = array();
          $transition =explode('=', $val);

          $result[$transition['0']] = $transition['1'];

        }
        return $result;
  	}


  	/**
  	 * 微信H5支付
  	 */
  	public static function wxPayH($request,$token)
  	{
        $money   = (int)$request['money'] ? : 0;
        
        //获取用户信息
        $userinfo = UserFactory::getUserByToken($token);
        
        $code = self::checkout($money,$userinfo);

        if($code!=1){
        	echo "<button onclick='javascript:history.go(-1)' style='width:100px; height:50px; lineheight:50px;display: block; margin: 20px auto;'>返回上一页</button>";die;
        }

        $money = $money/100;
        
        //money_log订单ID
        $orderid = TokenGenerator::generateToken();
        $insert = self::insertMoney($userinfo,$orderid,$money,1);
        if($insert!=1){
          return $insert;
        }

  		 //查询支付配置
        $pay = PaySetting::where("status",1)->where("type",3)->limit(1)->get()->toArray();
        
        $config = [
        	'appid'      => $pay['0']['extend'], // APP APPID
    			'app_id'     => $pay['0']['extend'], // 公众号 APPID
    			'mch_id'     => $pay['0']['mid'],
    			'key'        => $pay['0']['key'],
    			'notify_url' => $_SERVER['HTTP_HOST'].'/v1/recharge/wxnotify',
    		];

    		$order = [
          'out_trade_no' => $orderid,
          'total_fee'    => $money*100,
          'body'         => '幸运购'
  		  ];

		    $info = Pay::wechat($config)->wap($order);
        
        echo $info;die;
  	}


  	/**
  	 * 微信公众号支付
  	 */
  	public static function wxPublicPay($request,$token)
  	{
        $money   = (int)$request['money'] ? : 0;

        //获取用户信息
        $userinfo = UserFactory::getUserByToken($token);

        $code = self::checkout($money,$userinfo);

        if($code!=1){
        	return $code;
        }

        $money = $money/100;

        //money_log订单ID
        $orderid = TokenGenerator::generateToken();
        $insert = self::insertMoney($userinfo,$orderid,$money,1);
        if($insert!=1){
          return $insert;
        }

        //查询支付配置
        $pay = PaySetting::where("status",1)->where("type",3)->limit(1)->get()->toArray();

    		$order = [
            'out_trade_no' => $orderid,
            'body'         => '幸运购',
            'total_fee'    => $money*100,
            'openid'       => 'o9Fz6wzQwYXSFhdyADRnHKuSrpxc',
    		];
          
        $config = [
    			'app_id'     => $pay['0']['extend'], // 公众号 APPID
    			'mch_id'     => $pay['0']['mid'],
    			'key'        => $pay['0']['key'],
    			'notify_url' => $_SERVER['HTTP_HOST'].'/v1/recharge/wxnotify',
    		];


		    $info = Pay::wechat($config)->mp($order);
        $result = json_decode($info,true);
        return $result ? : array();
  	}


  	/**
  	 * 支付宝H5支付
  	 */
  	public static function aliPayH($request,$token)
  	{
        $money   = (int)$request['money'] ? : 0;

        //获取用户信息
        $userinfo = UserFactory::getUserByToken($token);
        
        $code = self::checkout($money,$userinfo);

        if($code!=1){
        	echo "<button onclick='javascript:history.go(-1)' style='width:100px; height:50px; lineheight:50px;display: block; margin: 20px auto;'>返回上一页</button>";die;
        }

        $money = $money/100;

        //money_log订单ID
        $orderid = TokenGenerator::generateToken();
        $insert = self::insertMoney($userinfo,$orderid,$money,2);
        if($insert!=1){
          return $insert;
        }

        //查询支付配置
        $pay = PaySetting::where("status",1)->where("type",2)->limit(1)->get()->toArray();

    		$config = [
  		    'app_id'         => $pay['0']['mid'],
          'notify_url'     => $_SERVER['HTTP_HOST'].'/v1/recharge/alinotify',
          'ali_public_key' => $pay['0']['extend'],
          'private_key'    => $pay['0']['key'],
          'return_url'     => 'http://test.m.anwenqianbao.com/#/recharge'
  		  ];

		    $order = [
          'out_trade_no' => $orderid,
          'total_amount' => $money,
          'subject'      => '幸运购',
		    ];

    		$result = Pay::alipay($config)->wap($order);
    		echo $result;die;
  	}

}
